# -*- coding: utf-8 -*-
'''生成趋势数据，格式为python tools/generate_cyclical_trend.py cq_ssc 20170305
'''
import os
import sys
import traceback

from dateutil import parser

base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(base_dir)
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "base.settings")

from common.timer.cyclical_handler import NEXT_TERM
from common.lottery.cyclical.model import ACTIVITY_LOGIC, ACTIVITY_MODEL, TREND_MODEL
from common.lottery.cyclical import ACTIVITY_STATUS
from common.lottery import KEYWORD_TYPE_DCT
from common.lottery.cyclical.cq_ssc.db import activity as cq_ssc_db
from common.lottery.cyclical.cq_lf.db import activity as cq_lf_db
from common.lottery.cyclical.tj_ssc.db import activity as tj_ssc_db
from common.lottery.cyclical.xj_ssc.db import activity as xj_ssc_db
from common.lottery.cyclical.gd_11x5.db import activity as gd_11x5_db
from common.lottery.cyclical.sd_11x5.db import activity as sd_11x5_db
from common.lottery.cyclical.jx_11x5.db import activity as jx_11x5_db
from common.lottery.cyclical.sh_11x5.db import activity as sh_11x5_db
from common.lottery.cyclical.js_ks.db import activity as js_ks_db
from common.lottery.cyclical.gx_ks.db import activity as gx_ks_db
from common.lottery.cyclical.bj_pk10.db import activity as bj_pk10_db
from common.lottery.cyclical.tc_pls.db import activity as tc_pls_db
from common.lottery.cyclical.fc3d.db import activity as fc3d_db
from common.lottery.cyclical.ff_ssc.db import activity as ff_ssc_db
from common.lottery.cyclical.ff_11x5.db import activity as ff_11x5_db
from common.lottery.cyclical.ff_ks.db import activity as ff_ks_db
from common.lottery.cyclical.ff_pk10.db import activity as ff_pk10_db

DB_DICT = {
    'cq_ssc': cq_ssc_db,
    'cq_lf': cq_lf_db,
    'sd_11x5': sd_11x5_db,
    'js_ks': js_ks_db,
    'tj_ssc': tj_ssc_db,
    'xj_ssc': xj_ssc_db,
    'gd_11x5': gd_11x5_db,
    'jx_11x5': jx_11x5_db,
    'sh_11x5': sh_11x5_db,
    'gx_ks': gx_ks_db,
    'bj_pk10': bj_pk10_db,
    'tc_pls': tc_pls_db,
    'fc3d': fc3d_db,
    'ff_ssc': ff_ssc_db,
    'ff_11x5': ff_11x5_db,
    'ff_ks': ff_ks_db,
    'ff_pk10': ff_pk10_db,
}


def run(key, date_str=None):
    db = DB_DICT[key]
    activity_type = KEYWORD_TYPE_DCT[key]
    ac_table = ACTIVITY_MODEL[activity_type]
    trend_table = TREND_MODEL[activity_type]
    logic = ACTIVITY_LOGIC[activity_type]
    last_term = None

    if date_str is None:
        last_stats = trend_table()
        last_stats.from_dict(trend_table.get_defaults())
        items = ac_table.query.filter(
            ac_table.status == ACTIVITY_STATUS.ANNOUNCED).order_by(
            ac_table.term).all()  # 从第一期开始所有期
    else:
        first_term = logic._format_term(parser.parse(date_str), 1)
        try:
            if activity_type in NEXT_TERM:
                first_term = logic.plus_term(first_term, -1)  # 前一天最后一期
                last_stats = trend_table.query.filter(
                    trend_table.term == first_term).one()
            else:
                last_stats = trend_table.query.filter(
                    trend_table.term < first_term).order_by(
                    trend_table.term.desc()).limit(1).one()
                first_term = last_stats.term
        except Exception as e:
            print 'term: ', first_term
            raise e
        items = ac_table.query.filter(
            ac_table.term > first_term).filter(
            ac_table.status == ACTIVITY_STATUS.ANNOUNCED).order_by(
            ac_table.term).all()  # 今天所有期
        last_term = first_term

    items = [item.as_dict() for item in items]

    for item in items:
        # 允许爬虫出现数据断层，仅打印警告
        term = item['term']
        if last_term is not None:
            if logic.plus_term(last_term, 1) != term:
                print 'NOTE: term interupt between (%s, %s)' % (
                    last_term, term)
        last_term = term
        number = item['number']
        try:
            last_stats = db.insert_stats(term, item['number'], last_stats)
        except Exception as e:
            print 'insert stats error', str(e)


if __name__ == '__main__':
    try:
        key = sys.argv[1]
    except Exception:
        raise ValueError('format: python xxx.py lottery_name date')
    date_str = sys.argv[2] if len(sys.argv) > 2 else None
    if key == 'all':
        for k in KEYWORD_TYPE_DCT:
            print k
            try:
                run(k, date_str)
            except Exception as e:
                traceback.print_exc()
    else:
        try:
            run(key, date_str)
        except Exception as e:
            traceback.print_exc()
